package com.thti.mecool.client.util;

import java.io.InputStream;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

/**
 * 图片异步加载
 * 
 * @author weiguo.ren
 * 
 */
public class AsyncImageLoader {
	public AsyncImageLoader() {
	}
	public Drawable loadDrawable(final String imageUrl,final ImageCallback callback) {
		try {
			Util.print("图片地址:"+imageUrl);
			if (ImageUtil.imageCache.containsKey(imageUrl)) {
				Drawable drawable = ImageUtil.get(imageUrl);
				if (null != drawable){
					return drawable; 
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				callback.imageLoaded((Drawable) msg.obj, StringUtil.isString(imageUrl));
			}
		};

		new Thread() {
			@Override
			public void run() {
				try {
					Drawable drawable = loadImageFromUrl(StringUtil.isString(imageUrl));
					if (null!=drawable) {
						ImageUtil.add(imageUrl, drawable);
						handler.sendMessage(handler.obtainMessage(0, drawable));
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		}.start();
		return null;
	}
	protected Drawable loadImageFromUrl(String imageUrl) {
		try {
			InputStream inputStream = NetTool.GET(StringUtil.isString(imageUrl));
			Drawable drawable= Drawable.createFromStream(inputStream, "src");
			return drawable;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public interface ImageCallback {
		public void imageLoaded(Drawable imageDrawable, String imageUrl);
	}
}
